package com.yanxiuhair.framework.shiro.web.filter.sync;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.shiro.web.filter.PathMatchingFilter;
import com.yanxiuhair.common.constant.ShiroConstants;
import com.yanxiuhair.framework.shiro.session.OnlineSession;
import com.yanxiuhair.framework.shiro.session.OnlineSessionDAO;

/**
 * @ClassName:  SyncOnlineSessionFilter   
 * @Description: 同步Session数据到Db 
 * @author: gaoxiaochuang   
 * @date:   2021年7月1日 下午4:45:14   
 *     
 * @Copyright: 2021 http://www.yanxiuhair.com/ Inc. All rights reserved. 
 * 注意：本内容仅限于许昌妍秀发制品有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
public class SyncOnlineSessionFilter extends PathMatchingFilter {
	private OnlineSessionDAO onlineSessionDAO;

	/**
	 * 同步会话数据到DB 一次请求最多同步一次 防止过多处理 需要放到Shiro过滤器之前
	 */
	@Override
	protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		OnlineSession session = (OnlineSession) request.getAttribute(ShiroConstants.ONLINE_SESSION);
		// 如果session stop了 也不同步
		// session停止时间，如果stopTimestamp不为null，则代表已停止
		if (session != null && session.getUserId() != null && session.getStopTimestamp() == null) {
			onlineSessionDAO.syncToDb(session);
		}
		return true;
	}

	public void setOnlineSessionDAO(OnlineSessionDAO onlineSessionDAO) {
		this.onlineSessionDAO = onlineSessionDAO;
	}
}
